package com.myblog.controller;

import com.myblog.service.QiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class UploadController {
    @Autowired
    QiniuService qiniuService;

    @Value("${baseUploadUrl}")
    private String url;
    @Value("${qiniu.path}")
    private String path;

    @PostMapping("/upload")
    public Map<String, Object> uploadImg(@RequestParam(value = "editormd-image-file", required = true) MultipartFile upload) throws IOException {
        Map<String, Object> map = new HashMap<>();
        String fileName = upload.getOriginalFilename();
        File file = new File(url + fileName);
        try {
            //将MulitpartFile文件转化为file文件格式
            upload.transferTo(file);
            Map response = qiniuService.uploadFile(file);
            Object imageName = response.get("imgName");
            map.put("url", path + "/" + imageName);
            map.put("success", 1);
            map.put("message", "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
